/**
 * 基础菜单 宠物管理
 */
<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>宠物管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 搜索筛选 -->
        <el-form :inline="true" :model="formInline" class="user-search">
            <el-form-item label="搜索：">
                <el-input size="small" v-model="formInline.pname" placeholder="输入宠物名称" clearable @clear="getdata"></el-input>
            </el-form-item>
            <!-- <el-form-item label="">
                <el-input size="small" v-model="formInline.deptNo" placeholder="输入部门代码"></el-input>
            </el-form-item> -->
            <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
                <el-button size="small" type="primary" icon="el-icon-refresh-right" @click="reset">重置</el-button>
                <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加</el-button>
                <el-button size="small" type="primary"  @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
        <!--列表-->
        <el-table 
            size="small" 
            :data="listData" 
            highlight-current-row 
            stripe
            v-loading="loading" 
            border 
            element-loading-text="拼命加载中" 
            style="width: 100%;">
            <el-table-column 
                align="center" 
                type="index" 
                width="60">
            </el-table-column>
            <el-table-column 
                prop="pname" 
                label="宠物名称">
            </el-table-column>
            <el-table-column 
                prop="age" 
                label="宠物年龄">
            </el-table-column>
            <el-table-column 
                prop="gender" 
                label="宠物性别">
            </el-table-column>
            <el-table-column 
                prop="kind" 
                label="宠物类型">
            </el-table-column>
            <el-table-column 
                prop="size" 
                label="宠物体型" >
                <!-- <template slot-scope="scope">
                    <div>{{scope.row.editTime|timestampToTime}}</div>
                </template> -->
            </el-table-column>
            <el-table-column 
                prop="weight" 
                label="宠物长度">
            </el-table-column>
            <el-table-column 
                prop="height" 
                label="宠物身高">
            </el-table-column>
            <el-table-column 
                prop="isTui" 
                v-slot="{row}"
                label="是否推选">
                <el-switch v-model="row.isTui" />
            </el-table-column>
            <el-table-column 
                align="center" 
                label="操作" 
                min-width="300">
                <template slot-scope="scope">
                    <el-button 
                        size="mini" 
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button 
                        size="mini" 
                        type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <!-- <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination> -->
        <!-- 编辑界面 -->
        <el-dialog 
            :title="title" 
            :visible.sync="editFormVisible"
            width="600px"
            top="5vh"
            @click="closeDialog">
            <el-form label-width="80px" :model="editForm" :rules="rules" ref="editForm">
                <el-form-item 
                    label="宠物名称" 
                    prop="pname">
                    <el-input 
                        size="small" 
                        v-model="editForm.pname" 
                        auto-complete="off" 
                        placeholder="请输入宠物名称"></el-input>
                </el-form-item>
                <el-form-item label="品种" 
                    prop="kind">
                    <el-radio-group v-model="editForm.kind">
                      <el-radio border :label="item.name" v-for="(item,idx) in kindList" :key="idx">
                      </el-radio>
                    </el-radio-group>
                    <!-- <el-input 
                        size="small" 
                        v-model="editForm.kind" 
                        auto-complete="off" 
                        placeholder="请输入品种"></el-input> -->
                </el-form-item>
                <el-form-item label="体型" 
                    prop="size">
                    <el-radio-group v-model="editForm.size">
                        <el-radio label="S" border></el-radio>
                        <el-radio label="M" border></el-radio>
                        <el-radio label="L" border></el-radio>
                        <el-radio label="XL" border></el-radio>
                    </el-radio-group>
                    <!-- <el-input 
                        size="small" 
                        v-model="editForm.size" 
                        auto-complete="off" 
                        placeholder="请输入体型"></el-input> -->
                </el-form-item>
                <el-form-item label="宠物图片" >
                    <div class="img-box">
                        <div v-if="imgList" class="flex">
                            <div v-for="(item,i) in imgList" :key="i" style="position: relative;">
                                <img :src="item" class="avatar" > 
                            <i class="el-icon-delete" style="color:red;cursor: pointer;position: absolute;
        top: 0;
        left: 40px;" @click="imgList.splice(i,1)"/>
                            </div>

                        </div>
                        <el-upload
                            class="avatar-uploader"
                            :on-success="handleAvatarSuccess"
                            action="http://localhost:3000/adopt/image"
                            :before-upload="beforeAvatarUpload"
                            :show-file-list="false"
                            :http-request="upLoad"
                            >
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </el-form-item>
                <el-form-item label="性别" 
                    prop="gender">
                    <el-radio-group v-model="editForm.gender">
                        <el-radio label="雄" border></el-radio>
                        <el-radio label="雌" border></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item 
                    label="年龄" 
                    prop="age">
                    <el-radio-group v-model="editForm.age">
                        <el-radio label="幼年" border></el-radio>
                        <el-radio label="青年" border></el-radio>
                        <el-radio label="成年" border></el-radio>
                        <el-radio label="老年" border></el-radio>
                    </el-radio-group>
                    <!-- <el-input-number 
                        size="small" 
                        v-model="editForm.age" 
                        auto-complete="off" 
                        placeholder="请输入年龄" 
                        controls-position="right"></el-input-number> -->
                </el-form-item>
                <el-form-item label="高度(cm)" >
                    <el-input-number 
                        size="small" 
                        v-model="editForm.height" 
                        auto-complete="off" 
                        placeholder="请输入高度" 
                        controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="宽度(cm)" >
                    <el-input-number 
                        size="small" 
                        v-model="editForm.weight" 
                        auto-complete="off" 
                        placeholder="请输入宽度" 
                        controls-position="right"></el-input-number>
                </el-form-item>
                <el-form-item label="颜色">
                    <el-input 
                        size="small" 
                        v-model="editForm.color" 
                        auto-complete="off" 
                        placeholder="请输入性别"></el-input>
                </el-form-item>
                <el-form-item label="分配机构" prop="mechanismId">
                    <el-select v-model="editForm.mechanismId" placeholder="请选择分配的机构">
                        <el-option
                            v-for="item in options"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否推选" prop="isTui">
                    <el-radio-group v-model="editForm.isTui">
                        <el-radio :label="true" border>是</el-radio>
                        <el-radio :label="false" border>否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="备注" >
                    <el-input 
                        type="textarea" 
                        v-model="editForm.details" 
                        placeholder="请输入备注"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog">取消</el-button>
                <el-button size="small" type="primary" :loading="okLoading" class="title" @click="submitForm('editForm')">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { addPet, updatePet, delPet } from '../../api/pet.js'
import { getpetInfo, getMechanismList } from '@/api/api.js'
import { getType,uploadImg} from '../../api/type'
import Pagination from '../../components/Pagination'
export default {
    data() {
        return {
            nshow: true, //switch开启
            fshow: false, //switch关闭
            loading: false, //是显示加载
            okLoading: false, //是显示加载
            editFormVisible: false, //控制编辑页面显示与隐藏
            title: '添加',
            editForm: {
                deptId: '',
                deptName: '',
                deptNo: '',
                token: localStorage.getItem('logintoken')
            },
            // rules表单验证
            rules: {
                pname: [{ required: true, message: '请输入宠物名称', trigger: 'blur' }],
                kind: [{ required: true, message: '请输入品种', trigger: 'blur' }],
                size: [{ required: true, message: '请输入体型', trigger: 'blur' }],
                gender: [{ required: true, message: '请输入性别', trigger: 'blur' }],
                age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
                mechanismId: [{ required: true, message: '请选择分配机构', trigger: 'change' }],
                isTui: [{ required: true, message: '请选择是否推选', trigger: 'change' }],
            },
            formInline: {
                token: localStorage.getItem('logintoken'),
                pname: ''
            },
            // 删除部门
            seletedata: {
                ids: '',
                token: localStorage.getItem('logintoken')
            },
            userparm: [], //搜索权限
            listData: [], //用户数据
            // 分页参数
            pageparm: {
                currentPage: 1,
                pageSize: 10,
                total: 10
            },
            kindList: [],
            options: [],
            imgList: [],

        }
    },
    // 注册组件
    components: {
        Pagination
    },
    mounted() {
        this.getdata(this.formInline)
        this.getKind()
        this.getMechanism()
    },

    /**
     * 里面的方法只有被调用才会执行
     */
    methods: {
        handleAvatarSuccess(res, file) {
            let obj  = URL.createObjectURL(file.raw);
            console.log(obj);
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
            this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        reset() { 
            this.formInline = { 
                pname: ''
            }
            this.getdata()
        },
        // 获取公司列表
        async getdata() {
            try{ 
                this.loading = true
                const data = await getpetInfo({...this.formInline})
                if(!data.success) return this.$message.error('获取宠物列表错误')
                this.listData = data.data
                this.pageparm.currentPage = this.formInline.page
                this.pageparm.pageSize = this.formInline.limit
                this.pageparm.total = this.listData.length || 0
                // 模拟数据结束
            }catch(e){ 
                console.log(e);
            }finally{ 
                this.loading = false
            }
        },
        // 分页插件事件
        callFather(parm) {
            this.formInline.page = parm.currentPage
            this.formInline.limit = parm.pageSize
            this.getdata(this.formInline)
        },
        // 搜索事件
        search() {
            this.getdata(this.formInline)
        },
        //显示编辑界面
        handleEdit(index,row) {
            this.editFormVisible = true
            if (row != undefined && row != 'undefined') {
                this.title = '修改'
                this.editForm = this._.cloneDeep(row)
                console.log(this.imgList);
                this.$set(this,'imgList',JSON.parse(row.profile))
            } else {
                console.log(this.imgList);
                this.title = '添加'
                this.$set(this,'imgList',[])
                this.editForm.deptId = ''
                this.editForm.deptName = ''
                this.editForm.deptNo = ''
            }
        },
        // 编辑、增加页面保存方法
        submitForm(editData) {
            this.$refs[editData].validate(valid => {
                if(!valid) return false
                try{ 
                    if(this.imgList.length < 1 )return this.$message.error('请至少上传一张图片')
                    this.okLoading = true
                    let methods = this.title === '修改' ? updatePet : addPet
                    for(let v of this.options){
                        if(this.editForm.mechanismId === v.id){
                        console.log(v);
                            this.editForm.mechanismName = v.name
                        }
                    }
                    methods({
                        ...this.editForm,
                        profile: JSON.stringify(this.imgList)
                        }).then(res => { 
                        if(!res.success) return this.$message.error('系统繁忙')
                        this.$message.success('添加宠物成功！')
                        this.editFormVisible = false
                        this.getdata()
                        this.editForm = {}
                        this.imgList = []
                    })
                }catch(e){
                    console.log(e);
                }finally{ 
                    this.okLoading = false
                }
            })
        },
        async getKind() { 
            try{ 
                const data =  await getType({})
                if(!data.success) return this.$message.error('系统繁忙')
                this.kindList = data.data
            }catch(e) { 
                console.log(e);
            }
        },
        async upLoad(file){
            let formDatas = new FormData()
            formDatas.append('file', file.file)
            console.log( file);
            try {
                await uploadImg(formDatas)         
            } catch (error) {
                this.imgList.push(error.url)
                // this.$set(this.formData,'img',error.url)
            }
        },
        // 删除公司
        deleteUser(index, row) {
            this.$confirm('确定要删除吗?', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                delPet({id:row.id})
                    .then(res => {
                    if (res.success) {
                        this.$message({
                        type: 'success',
                        message: '宠物已删除!'
                        })
                        this.getdata()
                    } else {
                        this.$message({
                        type: 'info',
                        message: '系统繁忙'
                        })
                    }
                    })
                    .catch(err => {
                    this.loading = false
                    this.$message.error('宠物删除失败，请稍后再试！')
                    })
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    })
                })
            },
        // 关闭编辑、增加弹出框
        closeDialog() {
            this.editFormVisible = false
            this.editForm = {}
            this.$set(this,'imgList',[])
        },
        reset() { 
            this.getdata(this.formInline)
            this.$set(this.formInline,'pname','')
        },
        async getMechanism() {
            try{
                const data = await getMechanismList({
                    ...this.formInline
                })
                if(!data.success) return this.$message.error('系统繁忙')
                this.options = data.data
            }catch(e) { 
                console.log(e);
            }
        },
    }
}
</script>

<style scoped>
.user-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border:1px dashed #b4bccc;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
    margin-right: 10px;
  }
    .img-box{ 
      display: flex;
      flex-wrap: wrap;
  }
  .flex{ 
      flex-wrap: wrap;
      display: flex;
  }
</style>

 
 